package com.yzt.config.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import com.yzt.base.service.UserDetailService;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private UserDetailService userDetailService;
	@Autowired
	private UserLoginSuccessHandler userLoginSuccessHandler;

	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(userDetailService).passwordEncoder(passwordEncoder());
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests().antMatchers("/accessError").permitAll()// 开发接口
				.anyRequest().authenticated()//
				.and()//
				.formLogin()//
				.loginProcessingUrl("/user_login").loginPage("/user_login")//
				.defaultSuccessUrl("/")//
				.failureUrl("/login_fail")//
				.successHandler(userLoginSuccessHandler)//
				.permitAll()//
				.and().logout()//
				.logoutUrl("/log_out").addLogoutHandler(new UserLogoutHandler())
				.logoutSuccessHandler(new UserLogoutSuccessHandler()).permitAll()//
				.and().sessionManagement()//
				.invalidSessionStrategy(new CustomInvalidSessionStrategy())//
				.and().exceptionHandling().accessDeniedPage("/accessError");//
		http.csrf().disable();
		http.headers().frameOptions().disable();
	}

	@Override
	public void configure(WebSecurity web) throws Exception {
		web.ignoring().antMatchers("/css/**", "/js/**");
	}

}
